#include "mainwindow.h"
#include "GxIAPI.h"
#include "./ui_mainwindow.h"
#include <QFileDialog>
#include <QProgressBar>
#include <QMessageBox>
#include <QThreadPool>
#include <QSerialPortInfo>
#include <QSerialPort>
#include "description/dahengcameradevice.h"
#include "description/RecognizeDevice.h"
#include "description/WordopControlLEDOperation.h"

//#include "video/daheng5000camera.h"

MainWindow* MainWindow::_instance = nullptr;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_pDefectDetectionDialog(nullptr)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 大恒相机驱动库初始化
    InitLib();

    // 参数文件
    m_strParameterPath = "D:/test/seat/SeatDetection.xml";

    _instance = this;

    InitSeatParameter();

    InitMainImageViewWidget();

    InitImageViewWidget();

    InitImageListWidget();

    AllocImageBuffer();

    InitStatusBar();

    InitHttpServer();

    InitVideoViewWidget();

    InitDevices();

    //InitSeatFacePostion();

    InitHardwareTest();
}

MainWindow::~MainWindow()
{
    FreeImageBuffer();

    int nTotal      = m_objSeatDetection.GetDetectionWindowInfo().GetImageTotal();

    for (int i = 0; i < nTotal; i++) {
        delete m_ppImageCameraViewWidgets[i];
    }
    delete m_ppImageCameraViewWidgets;

    for (int i = 0; i < nTotal; i++) {
        delete m_ppInfoWidgets[i];
    }
    delete m_ppInfoWidgets;

    UninitDevices();

    // 大恒相机驱动库逆初始化
    UninitLib();

    delete ui;
}

void MainWindow::InitLib(){
    GX_STATUS emStatus = GX_STATUS_SUCCESS;
    emStatus = GXInitLib();
    if (emStatus != GX_STATUS_SUCCESS)
    {
        QMessageBox msgBox;
        msgBox.setText("");
        msgBox.exec();
    }
}

void MainWindow::UninitLib(){
    GX_STATUS emStatus = GX_STATUS_SUCCESS;
    emStatus = GXCloseLib();
    if (emStatus != GX_STATUS_SUCCESS)
    {

    }
}

void MainWindow::InitSeatParameter(){
    m_objSeatDetection.ReadXML(m_strParameterPath);
}

void MainWindow::on_pushButtonParameter_clicked()
{
    m_pSeatParameterDialog = new SeatParameterDialog(m_objSeatDetection, this);
    if(QDialog::Accepted == m_pSeatParameterDialog->exec()){
        m_objSeatDetection = m_pSeatParameterDialog->GetSeatDetection();

        m_objSeatDetection.writeXML(m_strParameterPath);
    }
}

void MainWindow::InitMainImageViewWidget(){
    ui->widgetMainViewWidget->SetImage(QImage("d:/test/seat/seatface0.bmp"));
    ui->widgetMainViewWidget->SetImageResult(0);
    // 初始页面
    ui->stackedWidgetMain->setCurrentWidget(ui->pageMainTest);
}

void MainWindow::InitVideoViewWidget(){
    QList<Device *> devices = MainWindow::instance()->GetSeatDetection()->GetDescription().GetDevices();
    for(Device* pDevice : devices){
        if(pDevice->getClassName() == "DahengCameraDevice"){// 如果是相机的话
            CameraViewWidget* pWidget = new CameraViewWidget(this);
            pWidget->setMinimumSize(240, 160);
            pWidget->setMaximumSize(240, 160);
            ui->groupBoxSubCamera->layout()->addWidget(pWidget);

            m_vecpVideoWidgets.append(pWidget);
        }
    }

    QSpacerItem* vSpacer = new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Expanding);
    ui->groupBoxSubCamera->layout()->addItem(vSpacer);
}

void MainWindow::InitImageListWidget(){
    int nTotal      = m_objSeatDetection.GetDetectionWindowInfo().GetImageTotal();
    for(int i = 0;i < nTotal;i++){
        QListWidgetItem* pItem = new QListWidgetItem(QIcon(":/icon/res/icon/pic.png"),QString::number(i));
        ui->listWidgetImage->addItem(pItem);
    }
}

void MainWindow::InitImageViewWidget(){
    int nRow,nColumn,nTotal;
    nRow        = m_objSeatDetection.GetDetectionWindowInfo().GetImageRow();
    nColumn     = m_objSeatDetection.GetDetectionWindowInfo().GetImageCol();
    nTotal      = m_objSeatDetection.GetDetectionWindowInfo().GetImageTotal();

    m_ppImageCameraViewWidgets = new CameraViewWidget*[nTotal];
    m_ppInfoWidgets = new CameraInfoWidget*[nTotal];

    for (int i = 0; i < nTotal; i++) {
        m_ppInfoWidgets[i] = new CameraInfoWidget(this);

        m_ppImageCameraViewWidgets[i] = new CameraViewWidget(this);
        m_ppImageCameraViewWidgets[i]->setVisible(false);
    }
}

void MainWindow::InitStatusBar(){
    // 创建进度条
    QProgressBar *pProgressBar = new QProgressBar(ui->statusbar);
    pProgressBar->setMaximum(100);  // 设置最大值
    pProgressBar->setValue(0);      // 初始值设为0

    pProgressBar->setVisible(false);

    // 将进度条添加到状态栏（可选，直接显示在状态栏上）
    ui->statusbar->addPermanentWidget(pProgressBar);
}

void MainWindow::InitHttpServer(){
    m_objHttpServer.startServer(8888);
}

QString LongToIPv4String(unsigned int ip)
{
    return QString("%1.%2.%3.%4")
        .arg((ip >> 24) & 0xFF)
        .arg((ip >> 16) & 0xFF)
        .arg((ip >> 8) & 0xFF)
        .arg(ip & 0xFF);
}

QString uncharToQstring(unsigned char * id,int len)
{
    QString temp,msg;
    int j = 0;

    while (j<len)
    {
        temp = QString("%1").arg((int)id[j], 2, 16, QLatin1Char('0'));
        msg.append(temp);
        j++;
    }

    return msg;
}

void MainWindow::InitComboBoxDatas(){
    // (2) 串口号，获取所有可用的串口信息
    QList<QSerialPortInfo> serialPorts = QSerialPortInfo::availablePorts();
    ui->comboBoxSerialPort->clear();
    // 输出串口信息

    //qDebug() << "Available Serial Ports:";
    for (const QSerialPortInfo &serialPort : serialPorts) {
        //qDebug() << "Port: " << serialPort.portName() << "Description: " << serialPort.description();
        QString strSerialPort = QString("%1 %2").arg(serialPort.portName()).arg(serialPort.description());
        ui->comboBoxSerialPort->addItem(strSerialPort);
    }

    QList<Device *> devices = MainWindow::instance()->GetSeatDetection()->GetDescription().GetDevices();
    for(int i = 0; i < devices.count();i++){
        Device * pDevice = devices.at(i);

        if(pDevice->getClassName() == "RS232Device"){
            m_pRS232Device = (RS232Device*)pDevice;

            int nPort = ((RS232Device*)pDevice)->GetSPort();
            for(int i = 0;i < ui->comboBoxSerialPort->count();i++){
                QString strPort = ui->comboBoxSerialPort->itemText(i);
                QStringList strList = strPort.split(" ");
                if(strList.contains(QString("COM%1").arg(nPort))){
                    ui->comboBoxSerialPort->setCurrentIndex(i);
                }
            }

            // (3) 波特率
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud115200));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud57600));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud38400));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud19200));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud9600));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud4800));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud2400));
            ui->comboBoxBaudrate->addItem(QString::number(QSerialPort::BaudRate::Baud1200));
            ui->comboBoxBaudrate->setCurrentText(QString::number(((RS232Device*)pDevice)->GetBaud()));

            // (4) 数据位
            ui->comboBoxDatabits->addItem(QString::number(QSerialPort::DataBits::Data5));
            ui->comboBoxDatabits->addItem(QString::number(QSerialPort::DataBits::Data6));
            ui->comboBoxDatabits->addItem(QString::number(QSerialPort::DataBits::Data7));
            ui->comboBoxDatabits->addItem(QString::number(QSerialPort::DataBits::Data8));
            ui->comboBoxDatabits->setCurrentText(QString::number(((RS232Device*)pDevice)->GetDatabits()));

            // (5) 停止位
            ui->comboBoxStopbits->addItem("1 位",QVariant::fromValue(QSerialPort::StopBits::OneStop));
            ui->comboBoxStopbits->addItem("1.5 位",QVariant::fromValue(QSerialPort::StopBits::OneAndHalfStop));
            ui->comboBoxStopbits->addItem("2 位",QVariant::fromValue(QSerialPort::StopBits::TwoStop));
            for(int i = 0;i < ui->comboBoxStopbits->count();i++){
                if(((RS232Device*)pDevice)->GetStopbits() == QSerialPort::StopBits::OneStop){
                    ui->comboBoxStopbits->setCurrentIndex(0);
                }else if(((RS232Device*)pDevice)->GetStopbits() == QSerialPort::StopBits::OneAndHalfStop){
                    ui->comboBoxStopbits->setCurrentIndex(1);
                }else if(((RS232Device*)pDevice)->GetStopbits() == QSerialPort::StopBits::TwoStop){
                    ui->comboBoxStopbits->setCurrentIndex(2);
                }
            }

            // (6) 奇偶校验
            ui->comboBoxParity->addItem("无奇偶校验",QVariant::fromValue(QSerialPort::Parity::NoParity));
            ui->comboBoxParity->addItem("偶校验",QVariant::fromValue(QSerialPort::Parity::EvenParity));
            ui->comboBoxParity->addItem("奇校验",QVariant::fromValue(QSerialPort::Parity::OddParity));
            ui->comboBoxParity->addItem("Space",QVariant::fromValue(QSerialPort::Parity::SpaceParity));
            ui->comboBoxParity->addItem("Mark",QVariant::fromValue(QSerialPort::Parity::MarkParity));

            for(int i = 0;i < ui->comboBoxParity->count();i++){
                if(((RS232Device*)pDevice)->GetParity() == QSerialPort::Parity::NoParity){
                    ui->comboBoxParity->setCurrentIndex(0);
                }else if(((RS232Device*)pDevice)->GetParity() == QSerialPort::Parity::EvenParity){
                    ui->comboBoxParity->setCurrentIndex(1);
                }else if(((RS232Device*)pDevice)->GetParity() == QSerialPort::Parity::OddParity){
                    ui->comboBoxParity->setCurrentIndex(2);
                }else if(((RS232Device*)pDevice)->GetParity() == QSerialPort::Parity::SpaceParity){
                    ui->comboBoxParity->setCurrentIndex(3);
                }else if(((RS232Device*)pDevice)->GetParity() == QSerialPort::Parity::MarkParity){
                    ui->comboBoxParity->setCurrentIndex(4);
                }
            }
        }
    }

    // (7) 通道
    for(int i = 0;i < 4;i++)
        ui->comboBoxChannel->addItem(QString::number(i));

    // (8) 亮度
    for(int i = 0;i < 255;i++)
        ui->comboBoxValue->addItem(QString::number(i));
}

void MainWindow::InitComboCameras(QComboBox* pComboBox,int number){
    pComboBox->addItem("Camera1",QVariant::fromValue(number));
    pComboBox->addItem("Camera2",QVariant::fromValue(number));

    QVector<CameraInfo>& cameras = m_objSeatDetection.GetCameraInfos();
}

void MainWindow::InitSeatFaces(QComboBox* pComboBox,int number){
    pComboBox->addItem("A",QVariant::fromValue(number));
    pComboBox->addItem("B",QVariant::fromValue(number));
    pComboBox->addItem("C",QVariant::fromValue(number));
    pComboBox->addItem("D",QVariant::fromValue(number));
    pComboBox->addItem("E",QVariant::fromValue(number));
    pComboBox->addItem("F",QVariant::fromValue(number));
}

void MainWindow::InitSeatFacePostion(){
    //ui->widgetSeatFacePositon
    int nTotal = m_objSeatDetection.GetDetectionWindowInfo().GetSeatFaces().count();

    QGridLayout* pLayout = (QGridLayout*)ui->widgetSeatFacePositon->layout();
    QString strImageName;

    for(int i = 0; i  < nTotal / 2; i++){
        strImageName = QString("图像 %1").arg(i);

        QWidget* pWidget = new QLabel(strImageName);
        pLayout->addWidget(pWidget, i, 0);

        pWidget = new QComboBox();
        m_vecCameraIndexComboBoxs.append((QComboBox*)pWidget);
        pLayout->addWidget(pWidget, i, 1);
        InitComboCameras((QComboBox*)pWidget,i);

        pWidget = new QComboBox();
        m_vecFaceIndexComboBoxs.append((QComboBox*)pWidget);
        pLayout->addWidget(pWidget, i, 2);
        InitSeatFaces((QComboBox*)pWidget,i);
    }

    for(int i = nTotal / 2; i  < nTotal; i++){
        strImageName = QString("图像 %1").arg(i);

        QWidget* pWidget = new QLabel(strImageName);
        pLayout->addWidget(pWidget,i - nTotal / 2, 3);

        pWidget = new QComboBox();
        pLayout->addWidget(pWidget,i - nTotal / 2, 4);
        InitComboCameras((QComboBox*)pWidget,i);

        pWidget = new QComboBox();
        pLayout->addWidget(pWidget,i - nTotal / 2, 5);
        InitSeatFaces((QComboBox*)pWidget,i);
    }

    QPushButton* applyButton = new QPushButton("应用");
    pLayout->addWidget(applyButton, nTotal / 2 + nTotal % 2, 5);

    //connect(applyButton,&QPushButton::clicked,this,&MainWindow::on_pushbuttonApply_clicked);
}

void MainWindow::InitHardwareTest(){
    // (1) 初始化串口调试控制内容
    // 输出串口信息
    InitComboBoxDatas();

    // (2) 初始化相机调试控制内容
    // 定义表头内容：包括姓名、性别、出生日期、专业、是否毕业
    QStringList headList = {"生产厂家","设备型号","序列号","状态","IP地址"};
    //QStringList headList = {"IP地址"};

    // 设置表格的列数为表头的数量
    ui->tableWidgetCameras->setColumnCount(headList.count());

    // 遍历表头列表，设置每一列的表头项
    for (int i = 0; i < headList.size(); i++) {
        // 创建一个新的 QTableWidgetItem 对象，用于存储表头文本
        auto* item = new QTableWidgetItem(headList[i]);

        // 将表头项设置到表格的水平表头中
        ui->tableWidgetCameras->setHorizontalHeaderItem(i, item);
    }

    // 获取表格的水平表头对象，并设置列宽自动伸展模式
    auto* headerView = ui->tableWidgetCameras->horizontalHeader();
    headerView->setSectionResizeMode(QHeaderView::Stretch);

    int nCurrentRow = 0;
    QList<Device *> devices = MainWindow::instance()->GetSeatDetection()->GetDescription().GetDevices();
    for(int i = 0; i < devices.count();i++){
        Device * pDevice = devices.at(i);

        if(pDevice->getClassName() == "DahengCameraDevice"){
            nCurrentRow = ui->tableWidgetCameras->rowCount();
            ui->tableWidgetCameras->insertRow(nCurrentRow);

            QTableWidgetItem *pItem = new QTableWidgetItem(((DahengCameraDevice*)pDevice)->GetVendorName());
            ui->tableWidgetCameras->setItem(nCurrentRow,0,pItem);

            pItem = new QTableWidgetItem(((DahengCameraDevice*)pDevice)->GetDeviceModel());
            ui->tableWidgetCameras->setItem(nCurrentRow,1,pItem);

            pItem = new QTableWidgetItem(((DahengCameraDevice*)pDevice)->GetSerialNumber());
            ui->tableWidgetCameras->setItem(nCurrentRow,2,pItem);

            pItem = new QTableWidgetItem(((DahengCameraDevice*)pDevice)->GetIP());
            ui->tableWidgetCameras->setItem(nCurrentRow,4,pItem);
        }
    }
}

void MainWindow::AllocImageBuffer(){
    int totalImageCount = m_objSeatDetection.GetDetectionWindowInfo().GetImageTotal();
    m_nImageWidth = m_objSeatDetection.GetImageInfo().GetImageWidth();
    m_nImageHeight = m_objSeatDetection.GetImageInfo().GetImageHeight();
    m_nImageChannel = m_objSeatDetection.GetImageInfo().GetImageChannel();

    m_pImageSrcBuffer = (char*)malloc(m_nImageWidth * m_nImageHeight * m_nImageChannel * totalImageCount);
    m_pImageDestBuffer = (char*)malloc(m_nImageWidth * m_nImageHeight * m_nImageChannel * totalImageCount);
}

void MainWindow::FreeImageBuffer(){
    free(m_pImageSrcBuffer);
    free(m_pImageDestBuffer);
}

char* MainWindow::GetImageSrcBuffer(int index){
    char* pBuffer = m_pImageSrcBuffer + m_nImageWidth * m_nImageHeight * m_nImageChannel * index;
    return pBuffer;
}

char* MainWindow::GetImageDestBuffer(int index){
    char* pBuffer = m_pImageDestBuffer + m_nImageWidth * m_nImageHeight * m_nImageChannel * index;
    return pBuffer;
}

MainWindow* MainWindow::instance() {
    return _instance;
}

void MainWindow::PushDetectionResult(std::vector<Detection> detection){
    m_vecDetectionResults.push_back(detection);
}

std::vector<Detection> MainWindow::GetDetectionResult(int index){
    return m_vecDetectionResults.at(index);
}

void MainWindow::on_finishSanpImage_signal(int index){
    qDebug() << "MainWindow::on_finishSanpImage_signal(int index) " << QString::number(index);
    // 主窗口中显示当前图像的处理结果
    int imageWidth = m_objSeatDetection.GetImageInfo().GetImageWidth();
    int imageHeight = m_objSeatDetection.GetImageInfo().GetImageHeight();
    int imageChannel = m_objSeatDetection.GetImageInfo().GetImageChannel();
    char* pSrcBuffer = MainWindow::instance()->GetImageSrcBuffer(index);
    // 加载BMP图像
    QImage image(imageWidth,imageHeight,QImage::Format_BGR888);
    memcpy(image.bits(),pSrcBuffer,imageWidth * imageHeight * imageChannel);

    // 在检查对话框存在的情况下
    if(m_pDefectDetectionDialog != nullptr){
        CameraViewWidget** ppCameraViewWidget = MainWindow::instance()->GetImageCameraViewWidgets();
        CameraViewWidget* pCameraViewWidget = ppCameraViewWidget[index];

        pCameraViewWidget->SetInfo(QString::number(index));
        pCameraViewWidget->SetImageNum(index);
        pCameraViewWidget->SetImage(image);
    }
    // 在主图像框里显示当前图像
    ui->widgetMainViewWidget->SetImage(image);
    //image.save("E:\test.bmp");
}

void MainWindow::on_finishRecognizeImage_signal(int index){
    int imageWidth = m_objSeatDetection.GetImageInfo().GetImageWidth();
    int imageHeight = m_objSeatDetection.GetImageInfo().GetImageHeight();
    int imageChannel = m_objSeatDetection.GetImageInfo().GetImageChannel();

    qDebug() << "MainWindow::on_mySignal_signal(int index) " << QString::number(index);

    emit updateSubImage(index);
    // 主窗口中显示当前图像的处理结果
    char* pDestBuffer = MainWindow::instance()->GetImageDestBuffer(index);
    // 加载BMP图像
    QImage image(imageWidth,imageHeight,QImage::Format_BGR888);
    memcpy(image.bits(),pDestBuffer,imageWidth * imageHeight * imageChannel);
    ui->widgetMainViewWidget->SetImage(image);
}

void MainWindow::on_descriptionReceiveMessage(QString msg){
    emit sendReceivedMessage(msg);
}

void MainWindow::on_pushButtonRun_clicked()
{
    TocaputraCameraImage();

    if(m_pDefectDetectionDialog == nullptr){
        m_pDefectDetectionDialog = new DefectDetectionDialog(this);
        connect(this,&MainWindow::sendReceivedMessage,m_pDefectDetectionDialog,&DefectDetectionDialog::on_receiveMessage);
        connect(this,&MainWindow::updateSubImage,m_pDefectDetectionDialog,&DefectDetectionDialog::on_updateSubImage_signal);
        m_pDefectDetectionDialog->exec();
    }

    disconnect(this,&MainWindow::sendReceivedMessage,m_pDefectDetectionDialog,&DefectDetectionDialog::on_receiveMessage);
    disconnect(this,&MainWindow::updateSubImage,m_pDefectDetectionDialog,&DefectDetectionDialog::on_updateSubImage_signal);
    delete m_pDefectDetectionDialog;
    m_pDefectDetectionDialog = nullptr;

    RecaputraCameraVideo();
}

void MainWindow::on_pushButtonTest_clicked()
{
    //ui->widgetMainViewWidget->SetImageResult(1);
    ui->stackedWidgetMain->setCurrentIndex(0);
}

void MainWindow::on_pushButtonIndexDesign_clicked()
{
    //ui->widgetMainViewWidget->SetImageResult(0);

    //m_objSeatDetection.ReadXML(m_strParameterPath);
}

// 保存MainWindow中的图像为文件
void MainWindow::on_pushButtonSaveImage_clicked()
{
    // 设置默认的文件扩展名，例如.txt
    QString defaultExtension = "bmp";
    // 设置过滤字符串，例如"文本文件 (*.bmp)"
    QString filter = "文本文件 (*.bmp)";
    // 获取保存文件对话框的路径
    QString fileName = QFileDialog::getSaveFileName(this,
                                                    "保存文件",
                                                    "", // 默认目录，可以为空字符串，让系统决定默认目录
                                                    filter,
                                                    &defaultExtension); // 用于返回默认扩展名，可以为nullptr
    if (!fileName.isEmpty()) {
        // 用户选择了文件名，可以进一步处理或保存文件
        // 例如，你可以在这里写入文件内容：QFile file(fileName); file.open(QIODevice::WriteOnly); file.write("Hello, world!"); file.close();
        qDebug() << "保存的文件名为：" << fileName;

        QImage image = ui->widgetMainViewWidget->GetImage();
        image.save(fileName);
    } else {
        // 用户取消了操作或未选择任何文件
        qDebug() << "未选择文件";
    }
}

void MainWindow::on_pushButtonSanpImage_clicked()
{
    int imageNum = 0;
    int imageWidth = m_objSeatDetection.GetImageInfo().GetImageWidth();
    int imageHeight = m_objSeatDetection.GetImageInfo().GetImageHeight();
    int imageChannel = m_objSeatDetection.GetImageInfo().GetImageChannel();

    QListWidgetItem* item = ui->listWidgetImage->currentItem();
    if(item != nullptr){
        QString strImageNum = item->text();
        // 获取用户选择的图像编号
        imageNum = strImageNum.toInt();
        //
        DahengCameraDevice* pDahengCameraDevice = (DahengCameraDevice*)findCameraDeviceByImageName(imageNum);

        Step* pCurrentStep = MainWindow::instance()->GetSeatDetection()->GetDescription().GetStepByImageNum(imageNum);
        if(pCurrentStep != NULL){
            //DahengCameraDevice device;
            //device.SetIP("192.168.3.203");
            pDahengCameraDevice->initDevice();
            QMap<QString,QVariant> map;
            map.insert("content",QVariant(imageNum));
            pDahengCameraDevice->writeData(QVariant::fromValue(map));

            char* pSrcBuffer = MainWindow::instance()->GetImageSrcBuffer(imageNum);
            // 加载BMP图像
            QImage image(imageWidth,imageHeight,QImage::Format_BGR888);
            memcpy(image.bits(),pSrcBuffer,imageWidth * imageHeight * imageChannel);
            ui->widgetMainViewWidget->SetImage(image);

            image.save("D:\\test\\seat\\korol1.bmp");
        }
    }else{
        QMessageBox::information(this,"提示","请选择一副图像",QMessageBox::Yes);
    }
}

void MainWindow::on_pushButtonRecognizeImage_clicked()
{
    int imageNum = 0;
    QListWidgetItem* item = ui->listWidgetImage->currentItem();
    if(item != nullptr){
        QString strImageNum = item->text();
        imageNum = strImageNum.toInt();

        RecognizeDevice* pDevice = new RecognizeDevice();
        QMap<QString,QString> map;
        map.insert("content",QString::number(imageNum));
        pDevice->writeData(QVariant::fromValue(map));
    }else{
        QMessageBox::information(this,"提示","请选择一副图像",QMessageBox::Yes);
    }
}

Device* MainWindow::findCameraDeviceByImageName(int imageNum){
    QVector<SubImageInfo*>& subImageInfos = m_objSeatDetection.GetDetectionWindowInfo().GetSeatFaces();
    QVector<CameraInfo> cameraInfos = m_objSeatDetection.GetCameraInfos();
    QList<Device *> devices = m_objSeatDetection.GetDescription().GetDevices();

    for(SubImageInfo* pSubImageInfo : subImageInfos){
        if(pSubImageInfo->GetPosition() == imageNum){
            qDebug() << pSubImageInfo->GetCameraName();

            for(int i = 0;i < cameraInfos.count();i++){
                CameraInfo ci = cameraInfos.at(i);
                if(pSubImageInfo->GetCameraName() == ci.GetName()){

                    for(Device* pDevice : devices){
                        if(pDevice->getClassName() == "DahengCameraDevice"){
                            if(((DahengCameraDevice*)pDevice)->GetIP() == ci.GetIPAddress()){
                                return pDevice;
                            }
                        }
                    }
                }
            }
        }
    }
    return NULL;
}

void MainWindow::GetJakaRobotStatus(){
    if(m_pJakaRobotDevice->isConnect()){
        ui->pushButtonRobotConnect->setDisabled(false);
    }else{
        ui->pushButtonRobotConnect->setDisabled(true);
    }

    if(m_pJakaRobotDevice->isPower()){
        ui->pushButtonRobotPower->setDisabled(false);
    }else{
        ui->pushButtonRobotPower->setDisabled(true);
    }

    if(m_pJakaRobotDevice->isEnabled()){
        ui->pushButtonRobotEnable->setDisabled(false);
    }else{
        ui->pushButtonRobotEnable->setDisabled(true);
    }
}

void MainWindow::on_pushButtonRobotConnect_clicked()
{
    if(m_pJakaRobotDevice != NULL){
        m_pJakaRobotDevice->connect();
    }
}

void MainWindow::on_pushButtonRobotPower_clicked()
{
    if(m_pJakaRobotDevice != NULL){
        m_pJakaRobotDevice->power();
    }
}

void MainWindow::on_pushButtonRobotEnable_clicked()
{
    if(m_pJakaRobotDevice != NULL){
        m_pJakaRobotDevice->enable();
    }
}

void MainWindow::on_pushButtonRobotMove_clicked()
{
    QList<QVariant> variants;

    variants.append(ui->lineEditJoint1->text().toInt());
    variants.append(ui->lineEditJoint2->text().toInt());
    variants.append(ui->lineEditJoint3->text().toInt());
    variants.append(ui->lineEditJoint4->text().toInt());
    variants.append(ui->lineEditJoint5->text().toInt());
    variants.append(ui->lineEditJoint6->text().toInt());

    m_pJakaRobotDevice->writeData(variants);
}

void MainWindow::on_pushButtonOpenSerialPort_clicked()
{

}

void MainWindow::on_pushButtonSendData_clicked()
{
    WordopControlLEDOperation wclo;
    WORDOPCMD       objWordopCMD;

    objWordopCMD.identifier = 0x40;
    objWordopCMD.len = 0x05;
    objWordopCMD.code = 0x01;
    objWordopCMD.id = 0x00;
    objWordopCMD.wordopSubCmd.cmd = 0x1A;
    objWordopCMD.wordopSubCmd.channel = ui->comboBoxChannel->currentIndex();
    objWordopCMD.wordopSubCmd.data = ui->comboBoxValue->currentIndex();
    objWordopCMD.pWordopSubCmds = NULL;
    wclo.ChkSum(objWordopCMD);

    QByteArray bytes = wclo.ConvertCMD2Bytes(objWordopCMD);
    m_pRS232Device->writeData(QVariant(bytes));
}

void MainWindow::on_pushButtonTelescopicLeft_clicked()
{
    m_pJakaRobotDevice->SetDigitalOutput(0,1);
}

void MainWindow::on_pushButtonTelescopicRight_clicked()
{
    m_pJakaRobotDevice->SetDigitalOutput(0,1);
}

// 初始化所有的硬件外设
void MainWindow::InitDevices(){
    int index = 0;

    QList<Device*> devices = m_objSeatDetection.GetDescription().GetDevices();
    Device* pDevice = NULL;
    m_pJakaRobotDevice = NULL;

    for(int i = 0 ;i < devices.count();i++){
        pDevice = devices.at(i);
        // 初始化设备
        pDevice->initDevice();

        if(pDevice->getClassName() == "DahengCameraDevice"){
            // 设置显示的视频Widget
            ((DahengCameraDevice*)pDevice)->SetViedoWidget(m_vecpVideoWidgets.at(index++));

            ((DahengCameraDevice*)pDevice)->AcquisitionStart();
        }else if(pDevice->getClassName() == "JakaRobotDevice"){
            m_pJakaRobotDevice = (JakaRobotDevice*)pDevice;
        }
    }

    m_objSeatDetection.GetDescription().SetAllInitialized(true);
}

void MainWindow::UninitDevices(){
    QList<Device*> devices = m_objSeatDetection.GetDescription().GetDevices();
    Device* pDevice = NULL;
    m_pJakaRobotDevice = NULL;

    for(int i = 0 ;i < devices.count();i++){
        pDevice = devices.at(i);
        // 初始化设备
        pDevice->uninitDevice();
    }
}

void MainWindow::RecaputraCameraVideo(){
    QList<Device *> devices = MainWindow::instance()->GetSeatDetection()->GetDescription().GetDevices();
    for(int i = 0; i < devices.count();i++){
        Device * pDevice = devices.at(i);

        if(pDevice->getClassName() == "DahengCameraDevice"){
            ((DahengCameraDevice*)pDevice)->ConfigureCamera();

            ((DahengCameraDevice*)pDevice)->AcquisitionStart();
        }
    }
}

void MainWindow::TocaputraCameraImage(){
    QList<Device *> devices = MainWindow::instance()->GetSeatDetection()->GetDescription().GetDevices();
    for(int i = 0; i < devices.count();i++){
        Device * pDevice = devices.at(i);

        if(pDevice->getClassName() == "DahengCameraDevice"){

            ((DahengCameraDevice*)pDevice)->AcquisitionStop();

            ((DahengCameraDevice*)pDevice)->UnconfigureCamera();
        }
    }
}

void MainWindow::on_pushButtonArea_clicked()
{
    RecaputraCameraVideo();
}

void MainWindow::on_pushButtonHelp_clicked()
{
    /*QMap<QString,QVariant> map;
    map.insert("classname",QVariant("DahengCameraDevice"));
    map.insert("content",QVariant(0));
    pDevice->writeData(QVariant::fromValue(map));*/

    //TocaputraCameraImage();

    //m_ppInfoWidgets[0]->setParent(this);
}
